home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 12837 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.2 KB

  1. Path: mail2news.demon.co.uk!genesis.demon.co.uk
  2. From: Lawrence Kirby <fred@genesis.demon.co.uk>
  3. Newsgroups: comp.lang.c,comp.unix.programmer
  4. Subject: Re: Q: '\n' character
  5. Date: Wed, 03 Apr 96 01:01:59 GMT
  6. Organization: none
  7. Message-ID: <828493319snz@genesis.demon.co.uk>
  8. References: <31616F63.481D@lava.weeg.uiowa.edu> <4jrvv3$ask@aimnet.aimnet.com>
  9. Reply-To: fred@genesis.demon.co.uk
  10. X-NNTP-Posting-Host: genesis.demon.co.uk
  11. X-Newsreader: Demon Internet Simple News v1.27
  12. X-Mail2News-Path: genesis.demon.co.uk
  13.  
  14. In article <4jrvv3$ask@aimnet.aimnet.com>
  15.            jmcneill@aimnet.com "Jonathan S. McNeill" writes:
  16.  
  17. >In article <31616F63.481D@lava.weeg.uiowa.edu>,
  18. >Artur Wojdat  <awojdat@lava.weeg.uiowa.edu> wrote:
  19. >
  20. >>       Is there a function or some sort of way that I could remove '\n' 
  21. >>charecter form the end of the string. I'm reading from two files, want to 
  22. >>form one line of text and then have it printed out to stdout. I use fgets to 
  23. >>read from the file and I noticed that it appends newline char at the end.
  24.  
  25. The newline character is in the input stream, fgets() simply doesn't
  26. discard it like gets() does.
  27.  
  28. >/*
  29. > * loop through characters until newline or end of file
  30. > */
  31. >while ( (ch = getc(stream)) != '\n' && ch != EOF ) {
  32. >
  33. >        sprintf(buffer, "%s%c", buffer, ch);
  34.  
  35. This is truely horrific. You can't read and write to the same object with
  36. sprintf - the result is undefined behaviour. %s requires that you pass
  37. as the corresponding argument a pointer to a properly null character
  38. terminated string. There is no indication that buffer holds such a thing
  39. here.
  40.  
  41. >}
  42. >
  43. >/*
  44. > * add a trailing nul character so that you can use string functions
  45. > */
  46. >sprintf(buffer, "%s\0"); 
  47.  
  48. As far as a string is concerned "%s\0" is no different from "%s". There
  49. is an extra null character in there but a string always terminates at the
  50. first one so sprintf never sees the 2nd one. Also there's no argument
  51. corresponding to %s.
  52.  
  53. There is a simple trick to remove any trailing newline character in a string
  54. typically written by fgets(), say into buffer,  and that is:
  55.  
  56.    strtok(buffer, "\n");
  57.  
  58. -- 
  59. -----------------------------------------
  60. Lawrence Kirby | fred@genesis.demon.co.uk
  61. Wilts, England | 70734.126@compuserve.com
  62. -----------------------------------------
  63.